//
//  SubmitOrderViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/21.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "SubmitSerOrderModel.h"
#import "CommonExpressModel.h"

#import "NormalNaviView.h"
#import "SubmitOrderBottomView.h"

#import "AddressSelectView.h"

#import "SubmitOrderSectionHeader.h"
#import "SubmitOrderSectionFooter.h"


#import "OrderProductCell.h"
#import "SubmitOrderMarkCell.h"
#import "SubmitOrderItemActionCell.h"
#import "SubmitOrderItemShowCell.h"

#import "AddressManagerViewController.h"
#import "SelPayMethodViewController.h"

#import "SubmitOrderViewController.h"
#import "CouponUseCollectViewController.h"

#import "CommonCouponModel.h"

@interface SubmitOrderViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NormalNaviView *naviView;

@property (nonatomic, strong) AddressSelectView *addressView;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) SubmitOrderBottomView *bottomView;

@property (nonatomic, strong) SubmitSerOrderModel *submitModel;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*sellerSysCoupon;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*platformSysCoupon;

@property (nonatomic, strong) CommonExpressModel *sellerExpress;

//商品总额
@property (nonatomic, assign) double goodsTotal;

//商品运费
@property (nonatomic, assign) double seFreight;

//隐藏平台选券
@property (nonatomic, assign) BOOL isHidePcoupon;
//隐藏商家选券
@property (nonatomic, assign) BOOL isHideScoupon;

@end

@implementation SubmitOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self prepareData];
    [self request_submitInfoWithType:CouponUseType_none AndScoId:@""];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)prepareData {
        
    //默认不隐藏选券入口
    self.isHidePcoupon = NO;
    self.isHideScoupon = NO;

    self.submitModel.payType = 3;
    self.submitModel.goodsType = 2;

    self.submitModel.userId = [TTUserModel sharedObject].userId;
    self.submitModel.sellerId = self.dataArray.firstObject.sellerId;
    self.submitModel.serviceTime = @"";

    self.submitModel.bySellerVoList = @[].mutableCopy;
    
    HandleProSerStoreModel *storeModel = [[HandleProSerStoreModel alloc] init];
    storeModel.sellerId = self.dataArray.firstObject.sellerId;
    storeModel.sellerName = self.dataArray.firstObject.sellerModel.sellerName;
    storeModel.byGoodsVoList = @[].mutableCopy;
    double totalMoney = 0;
    
    for (CommonShopCartModel *shopCartmodel in self.dataArray) {
        HandleProSerModel *goodsModel = [[HandleProSerModel alloc] init];

        goodsModel.goodsId = shopCartmodel.sellerGoodsSpecs.sgsId;
        goodsModel.goodsPrice = shopCartmodel.sellerGoodsSpecs.specPrice;
        goodsModel.goodsNum = shopCartmodel.goodsNum;
        totalMoney = totalMoney + (shopCartmodel.sellerGoodsSpecs.specPrice * shopCartmodel.goodsNum);
        [storeModel.byGoodsVoList addObject:goodsModel];
    }
    [self.submitModel.bySellerVoList addObject:storeModel];

    self.submitModel.totalAmount = totalMoney;
}

//根据某个选券位置选中免单券  来释放对应券使用的选中情况
/*
 选中商家免单券----释放平台券、隐藏平台券选择位置
 选中平台免单券----释放商家券、隐藏商家券选择位置
 */
- (void)selFreeCouponWithType:(CouponUseType)type {
    switch (type) {
        case CouponUseType_store:{
            self.isHidePcoupon = YES;
            self.isHideScoupon = NO;

            self.submitModel.discountPcId = @"";
            self.submitModel.discountPcAmount = 0;
            
        } break;
        case CouponUseType_platform:{
            self.isHidePcoupon = NO;
            self.isHideScoupon = YES;
            
            self.submitModel.discountMcId = @"";
            self.submitModel.discountMcAmount = 0;
            
        } break;
        default:
            break;
    }
    
}

//选中免单券，取消的时候刷新UI
- (void)refreshFreeCouponUIStatus {
    self.isHidePcoupon = NO;
    self.isHideScoupon = NO;
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)initView {
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif

    self.view.backgroundColor = UIColorHex(0xf0f0f0);
    
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(0, 1);
    
    layer.colors = @[(__bridge id)[UIColorHex(0xff4242) colorWithAlphaComponent:1].CGColor, (__bridge id)[UIColorHex(0xf0f0f0) colorWithAlphaComponent:1].CGColor];
    
    layer.frame = CGRectMake(0, 0, TTScreenWidth, TTScreenWidth * 0.826);
    [self.view.layer insertSublayer:layer atIndex:0];
    
    

    [self.view addSubview:self.naviView];
    [self.view addSubview:self.tableview];
    
    self.addressView =  [[NSBundle mainBundle] loadNibNamed:@"AddressSelectView"owner:nil options:nil].firstObject;
    self.addressView.frame = CGRectMake(0, 0, TTScreenWidth, 112);

    self.tableview.tableHeaderView = self.addressView;
    self.addressView.autoresizingMask = UIViewAutoresizingNone;
    
    self.bottomView =  [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderBottomView"owner:nil options:nil].firstObject;
    [self.view addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(Bottom_SafeHeight + 60);
    }];
    self.bottomView.handleBtnWidth.constant = TTScreenWidth - 32;
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(kStatusBarHeight);
        make.height.mas_equalTo(44);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(self.bottomView.mas_top);
        make.top.mas_equalTo(self.naviView.mas_bottom);
    }];
    
    
    [self initViewAction];
}

- (void)initViewAction {
    
    self.addressView.userInteractionEnabled = YES;
    
    WEAKSELF
    [self.addressView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        AddressManagerViewController *vc = [[AddressManagerViewController alloc] init];
        
        vc.changeAddress = ^(AddressItemModel * _Nonnull model) {
            [weakSelf.addressView fillCellWithModel:model];
            
            weakSelf.submitModel.name = model.userName;
            weakSelf.submitModel.tel = model.phone;
            weakSelf.submitModel.address = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.area,model.address];
        };
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    self.bottomView.SubmitOrderBottomViewBlock = ^{

        if (weakSelf.submitModel.address.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请选择地址"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        }
        
        [weakSelf request_submitOrder];
    };
    
}

- (void)selectCouponWithDataArray:(NSMutableArray <CommonCouponModel *>*)dateArray Type:(CouponUseType)type {
    
    if (dateArray.count == 0) {
        switch (type) {
            case CouponUseType_platform: {
                 [SVProgressHUD showErrorWithStatus:@"无可用平台津贴"];
                 [SVProgressHUD dismissWithDelay:1];
            } break;
            case CouponUseType_store: {
                 [SVProgressHUD showErrorWithStatus:@"无可用优惠券"];
                 [SVProgressHUD dismissWithDelay:1];
            } break;
            default:
                break;
        }
        return;
    }
    
    WEAKSELF
    CouponUseCollectViewController *pop = [[CouponUseCollectViewController alloc]initDefaultHeight:0.6*TTScreenHeight vc:self dataSource:dateArray.mutableCopy type:type];
    STPopupController *popVericodeController = [[STPopupController alloc] initWithRootViewController:pop];
    popVericodeController.style = STPopupStyleBottomSheet;
    [popVericodeController presentInViewController:self];
    pop.selectIndex = ^(NSInteger index, CouponUseType type) {
        
        switch (type) {
            case CouponUseType_store:{//选择了一个店铺优惠券
                
                if (index>=0 && index <weakSelf.sellerSysCoupon.count) {
                    
                    CommonCouponModel *model = weakSelf.sellerSysCoupon[index];
                    weakSelf.submitModel.discountMcId = weakSelf.sellerSysCoupon[index].ucId;
                    weakSelf.submitModel.discountMcAmount = weakSelf.sellerSysCoupon[index].scoCut;
                    weakSelf.submitModel.isRecMc = weakSelf.sellerSysCoupon[index].isRec;

                    if (model.scoType == CouponType_userNew) {
                        [weakSelf selFreeCouponWithType:CouponUseType_store];
                    } else {
                        [weakSelf refreshFreeCouponUIStatus];
                    }
                    
                } else {
                    weakSelf.submitModel.discountMcId = @"";
                    weakSelf.submitModel.discountMcAmount = 0;
                    weakSelf.submitModel.isRecMc = NO;

                    //取消选中券 重置状态
                    [weakSelf refreshFreeCouponUIStatus];
                }
                //修改券的选中以及刷新tableview 这个在弹出里面显示
                [weakSelf refreshDataArray:weakSelf.sellerSysCoupon AndSelectIndex:index];
                //请求另一个类型的优惠券组
                [weakSelf request_submitInfoWithType:type AndScoId:weakSelf.submitModel.discountMcId];
                
            } break;
            case CouponUseType_platform:{//选择了一个商家优惠券
                
                if (index>=0 && index <weakSelf.platformSysCoupon.count) {
                    CommonCouponModel *model = weakSelf.platformSysCoupon[index];
                    weakSelf.submitModel.discountPcId = model.ucId;
                    weakSelf.submitModel.discountPcAmount = model.scoCut;
                    weakSelf.submitModel.isRecPc = weakSelf.platformSysCoupon[index].isRec;

                    if (model.scoType == CouponType_userNew) {
                        weakSelf.submitModel.discountPcAmount = CouponSubmitType_userNew;
                    }
                    
                    if (model.scoType == CouponType_userNew) {
                        [weakSelf selFreeCouponWithType:CouponUseType_platform];
                    } else {
                        [weakSelf refreshFreeCouponUIStatus];
                    }
                    
                } else {
                    weakSelf.submitModel.discountPcId = @"";
                    weakSelf.submitModel.discountPcAmount = 0;
                    weakSelf.submitModel.isRecPc = NO;

                    [weakSelf refreshFreeCouponUIStatus];
                }
                //修改券的选中以及刷新tableview
                [weakSelf refreshDataArray:weakSelf.platformSysCoupon AndSelectIndex:index];
                
                [weakSelf request_submitInfoWithType:type AndScoId:weakSelf.submitModel.discountPcId];

            } break;
            default:
                break;
        }
        
        [weakSelf.tableview reloadData];
    };
}

- (void)refreshDataArray:(NSMutableArray <CommonCouponModel *>*)dataArray AndSelectIndex:(NSInteger)index {
    
    for (CommonCouponModel *model in dataArray) {
        model.isSel = NO;
    }
    
    if (index >=0 && index < dataArray.count) {
        dataArray[index].isSel = YES;
    }
    [self.tableview reloadData];
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    switch (section) {
        case SubmitOrderSectionType_sellItem:{
            return self.dataArray.count;
        } break;
        case CouponUseType_platform_remark:{
            return 1;
        } break;
        case SubmitOrderSectionType_info:{
            return 4;
        } break;
        default:
            break;
    }
    
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case SubmitOrderSectionType_sellItem:{
            return 80;
        } break;
        case CouponUseType_platform_remark:{
            return 50;
        } break;
        case SubmitOrderSectionType_info:{
            
            switch (indexPath.row) {
                case SubmitOrderInfoRowType_itemMoney:{
                } break;
                case SubmitOrderInfoRowType_itemScoupon:{
                    if (self.isHideScoupon) {
                        return CGFLOAT_MIN;
                    }
                } break;
                case SubmitOrderInfoRowType_itemPcoupon:{
                    if (self.isHidePcoupon) {
                        return CGFLOAT_MIN;
                    }
                } break;
                case SubmitOrderInfoRowType_itemExpressMoney:{
                } break;
                default:
                    break;
            }
            
            return 40;
        } break;
        default:
            break;
    }
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

#pragma mark sectionheader
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    SubmitOrderSectionHeader *headView  =  [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderSectionHeader"owner:nil options:nil].firstObject;
    return  headView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    SubmitOrderSectionFooter *footerView  =  [[NSBundle mainBundle] loadNibNamed:@"SubmitOrderSectionFooter"owner:nil options:nil].firstObject;
    return  footerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    switch (indexPath.section) {
        case SubmitOrderSectionType_sellItem:{

            OrderProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderProductCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            [cell fillCellWithModel:self.dataArray[indexPath.row]];
            return cell;
            
        } break;
        case CouponUseType_platform_remark:{

            SubmitOrderMarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderMarkCellID"];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
            cell.orderMarkTF.text = self.submitModel.remark;
            
            cell.textFieldChangeBlock = ^(NSString * _Nonnull content) {
              
                weakSelf.submitModel.remark = content;
            };
            
            return cell;
            
        } break;
        case SubmitOrderSectionType_info:{

            
            switch (indexPath.row) {
                case SubmitOrderInfoRowType_itemMoney:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemSubTitle.hidden = YES;

                    cell.itemTitle.text = @"商品金额";
                    cell.itemContent.text =[NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.goodsTotal]];

                    return cell;
                    
                } break;
                case SubmitOrderInfoRowType_itemScoupon:{
                    
                    SubmitOrderItemActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemActionCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"优惠券";
                    cell.itemSubTitle.hidden = YES;
                    if (self.submitModel.discountMcAmount > 0) {
                        cell.itemContent.textColor = UIColorHex(0xFF2442);
                        cell.itemContent.text =[NSString stringWithFormat:@"-¥%@",[Utilities changeDoubleToString:self.submitModel.discountMcAmount]];
                        cell.tagBtn.hidden = !self.submitModel.isRecMc;
                    } else {
                        cell.itemContent.textColor = UIColorHex(0xCDCDCD);
                        cell.itemContent.text = [NSString stringWithFormat:@"%ld张券可选",self.sellerSysCoupon.count];
                        cell.tagBtn.hidden = YES;
                    }
                    
                    return cell;
                    
                } break;
                case SubmitOrderInfoRowType_itemPcoupon:{
                    
                    SubmitOrderItemActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemActionCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemTitle.text = @"平台津贴";
                    cell.itemSubTitle.hidden = YES;
                    if (self.submitModel.discountPcAmount > 0) {
                        cell.itemContent.textColor = UIColorHex(0xFF2442);
                        cell.itemContent.text =[NSString stringWithFormat:@"-¥%@",[Utilities changeDoubleToString:self.submitModel.discountPcAmount]];
                        cell.tagBtn.hidden = !self.submitModel.isRecPc;
                    } else {
                        
                        if (self.submitModel.discountPcAmount == CouponSubmitType_userNew) {
                            cell.itemContent.textColor = UIColorHex(0xFF2442);
                            cell.itemContent.text =@"免单券";
                            cell.tagBtn.hidden = !self.submitModel.isRecPc;
                        } else {
                            
                            cell.itemContent.textColor = UIColorHex(0xCDCDCD);
                            cell.itemContent.text = [NSString stringWithFormat:@"%ld张券可选",self.platformSysCoupon.count];
                            cell.tagBtn.hidden = YES;
                        }
                    }
                    
                    return cell;
                    
                } break;
                case SubmitOrderInfoRowType_itemExpressMoney:{
                    
                    SubmitOrderItemShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubmitOrderItemShowCellID"];
                    cell.selectionStyle =UITableViewCellSelectionStyleNone;
                    cell.itemSubTitle.hidden = YES;

                    cell.itemTitle.text = @"运费";
                    
                    if (self.sellerExpress.seFreight > 0) {

                        cell.itemContent.text = [NSString stringWithFormat:@"满¥%@减¥%@",[Utilities changeDoubleToString:self.sellerExpress.seFreeFreight],[Utilities changeDoubleToString:self.sellerExpress.seFreight]];

                    } else {
                        cell.itemContent.text = @"免运费";
                    }

                    return cell;
                    
                } break;
                default:
                    break;
            }
            
        } break;
        default:
            break;
    }
    
    OrderProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderProductCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
        WEAKSELF
        switch (indexPath.section) {
            case SubmitOrderSectionType_sellItem:{
            } break;
            case CouponUseType_platform_remark:{
            } break;
            case SubmitOrderSectionType_info:{
                
                switch (indexPath.row) {
                    case SubmitOrderInfoRowType_itemMoney:{
                    } break;
                    case SubmitOrderInfoRowType_itemScoupon:{
                        [weakSelf selectCouponWithDataArray:self.sellerSysCoupon Type:CouponUseType_store];

                    } break;
                    case SubmitOrderInfoRowType_itemPcoupon:{
                        [weakSelf selectCouponWithDataArray:self.platformSysCoupon Type:CouponUseType_platform];

                    } break;
                    case SubmitOrderInfoRowType_itemExpressMoney:{

                    } break;
                    default:
                        break;
                }
            } break;
            default:
                break;
        }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  [UIColor clearColor];
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"OrderProductCell" bundle:nil] forCellReuseIdentifier:@"OrderProductCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderMarkCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderMarkCellID"];

        
        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderItemShowCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderItemShowCellID"];

        [_tableview registerNib:[UINib nibWithNibName:@"SubmitOrderItemActionCell" bundle:nil] forCellReuseIdentifier:@"SubmitOrderItemActionCellID"];

    }
    return _tableview;
}

- (NormalNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[NSBundle mainBundle] loadNibNamed:@"NormalNaviView"owner:nil options:nil].firstObject;
        _naviView.backgroundColor = UIColor.clearColor;
        _naviView.titleLab.text = @"确认订单";
        _naviView.rightItem.hidden = YES;
        [_naviView.backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _naviView;
    
}

- (NSMutableArray<CommonShopCartModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (SubmitSerOrderModel *)submitModel {
    if (!_submitModel) {
        _submitModel = [[SubmitSerOrderModel alloc] init];
    }
    return _submitModel;
}

//商家优惠券
- (NSMutableArray<CommonCouponModel *> *)sellerSysCoupon {
    if (!_sellerSysCoupon) {
        _sellerSysCoupon = @[].mutableCopy;
    }
    return _sellerSysCoupon;
}

//平台津贴
- (NSMutableArray<CommonCouponModel *> *)platformSysCoupon {
    if (!_platformSysCoupon) {
        _platformSysCoupon = @[].mutableCopy;
    }
    return _platformSysCoupon;
}

//计算总价
- (void)calculateTotalPay {
    //算出商品总价
    self.goodsTotal = 0;
    double total = 0;
    for (CommonShopCartModel *model in self.dataArray) {
        total = total + (model.goodsNum * model.sellerGoodsSpecs.specPrice);
        self.goodsTotal = total;
    }
    
    double cut = self.submitModel.discountMcAmount + self.submitModel.discountPcAmount;
    
    if (total - cut > 0) {
        self.submitModel.totalAmount = total - cut;
    } else {
        self.submitModel.totalAmount = 0;
    }
    
    //
    if (self.submitModel.totalAmount >= self.sellerExpress.seFreeFreight) {
        self.seFreight = 0;
    } else {
        self.seFreight = self.sellerExpress.seFreight;
    }
    
    self.submitModel.totalAmount = self.submitModel.totalAmount + self.seFreight;
    
    
    self.bottomView.totalMoneyLab.text = [NSString stringWithFormat:@"¥%@",[Utilities changeDoubleToString:self.submitModel.totalAmount]];
    
    self.bottomView.tagLab.hidden = YES;
    self.bottomView.totalMoneyLab.hidden = YES;
}

//请求提交订单数据，根据用券情况算出钱
- (void)request_submitInfoWithType:(CouponUseType)type AndScoId:(NSString *)scoId {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].cityId forKey:@"scoCityId"];
    [dic setValue:[TTUserModel sharedObject].cityName forKey:@"cityName"];
    
    //商品数组
    //sku数组
    NSMutableArray *skuVo = @[].mutableCopy;
    NSMutableArray *goodsId = @[].mutableCopy;
    for (CommonShopCartModel *model in self.dataArray) {
        
        if (model.goodsId.length > 0) {
            if (![goodsId containsObject:model.goodsId]) {
                [goodsId addObject:model.goodsId];
            }
        }
        
        NSDictionary *sku = @{}.mutableCopy;
        [sku setValue:@(model.sellerGoodsSpecs.specPrice) forKey:@"skuPrice"];
        [sku setValue:@(model.goodsNum) forKey:@"skuNum"];
        [sku setValue:model.sellerGoodsSpecs.sgsId forKey:@"skuId"];
        [skuVo addObject:sku];
    }
    [dic setValue:goodsId forKey:@"goodsId"];
    [dic setValue:skuVo forKey:@"skuVo"];

    [dic setValue:self.submitModel.sellerId forKey:@"sellerId"];

    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
        
    if (type != CouponUseType_none) {
        [dic setValue:@((CouponUseType)type) forKey:@"scoCouponType"];
        [dic setValue:scoId forKey:@"scoId"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SubmitEditOrder];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];

    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                


                NSArray *sellerSysCoupon = [resultDic valueForKey:@"sellerSysCoupon"];
                NSArray *platformSysCoupon = [resultDic valueForKey:@"platformSysCoupon"];
//seFreight
                NSDictionary *sellerExpress = [resultDic valueForKey:@"sellerExpress"];

                weakSelf.seFreight = [[resultDic valueForKey:@"seFreight"] doubleValue];
                
                if ([sellerExpress isKindOfClass:[NSDictionary class]]) {
                    weakSelf.sellerExpress = [CommonExpressModel modelWithDictionary:sellerExpress];
                }
                
                if ([sellerSysCoupon isKindOfClass:[NSArray class]]) {
                    
                    if (sellerSysCoupon.count > 0) {
                        weakSelf.sellerSysCoupon = @[].mutableCopy;
                        for (int i = 0; i < sellerSysCoupon.count; i++) {
                            NSDictionary *sellerSysCouponDic = sellerSysCoupon[i];
                            CommonCouponModel *model = [CommonCouponModel modelWithDictionary:sellerSysCouponDic];
                            if (model.couponUsa == 1) {
                                model.calSel = YES;
                            } else {
                                model.calSel = NO;
                            }
                            [weakSelf.sellerSysCoupon addObject:model];
                        }
                    }
                }
                
                if ([platformSysCoupon isKindOfClass:[NSArray class]]) {
                    
                    if (platformSysCoupon.count > 0) {
                        weakSelf.platformSysCoupon = @[].mutableCopy;
                        for (int i = 0; i < platformSysCoupon.count; i++) {
                            NSDictionary *platformSysCouponDic = platformSysCoupon[i];
                            CommonCouponModel *model = [CommonCouponModel modelWithDictionary:platformSysCouponDic];
                            if (model.couponUsa == 1) {
                                model.calSel = YES;
                            } else {
                                model.calSel = NO;
                            }
                            [weakSelf.platformSysCoupon addObject:model];
                        }
                    }
                }

                if (type == CouponUseType_none) {

                    [weakSelf configBestCouponWith:resultDic];
                    
                    
                    NSDictionary *defaultAddress = [resultDic valueForKey:@"defaultAddress"];
                    if ([defaultAddress isKindOfClass:[NSDictionary class]]) {
                        
                        AddressItemModel *model = [AddressItemModel modelWithDictionary:defaultAddress];
                        [weakSelf.addressView fillCellWithModel:model];

                        weakSelf.submitModel.name = model.userName;
                        weakSelf.submitModel.tel = model.phone;
                        weakSelf.submitModel.address = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.area,model.address];
                    }
                }
                
                [weakSelf calculateTotalPay];
                [weakSelf.tableview reloadData];
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];

    }];
}

//获取最佳优惠券搭配
- (void)configBestCouponWith:(NSDictionary *)resultDic {
    
    NSDictionary* isBestSellerSysCoupon = [resultDic valueForKey:@"isBestSellerSysCoupon"];
    NSDictionary* isBestPlatformSysCoupon = [resultDic valueForKey:@"isBestPlatformSysCoupon"];
//
    CommonCouponModel *sellerCouponModel = [CommonCouponModel modelWithDictionary:isBestSellerSysCoupon];
    CommonCouponModel *sysCouponModel = [CommonCouponModel modelWithDictionary:isBestPlatformSysCoupon];
    
    if (sellerCouponModel.scoCut > 0) {
        self.submitModel.discountMcId = sellerCouponModel.ucId;
        self.submitModel.discountMcAmount = sellerCouponModel.scoCut;
        self.submitModel.isRecMc = YES;
    }

    if (sysCouponModel.scoType == CouponType_userNew) {
        [self selFreeCouponWithType:CouponUseType_platform];
        self.submitModel.discountPcAmount = CouponSubmitType_userNew;
        self.submitModel.discountPcId = sysCouponModel.ucId;
//        self.submitModel.discountPcAmount = sysCouponModel.scoCut;
        self.submitModel.isRecPc = YES;
    }
    
    if (sysCouponModel.scoCut > 0) {
        self.submitModel.discountPcId = sysCouponModel.ucId;
        self.submitModel.discountPcAmount = sysCouponModel.scoCut;
        self.submitModel.isRecPc = YES;
    }
    
    for (CommonCouponModel *model in self.sellerSysCoupon) {
        
        if ([model.ucId isEqualToString:sellerCouponModel.ucId]) {
            NSInteger index = [self.sellerSysCoupon indexOfObject:model];
            self.sellerSysCoupon[index].isRec = YES;
            [self refreshDataArray:self.sellerSysCoupon AndSelectIndex:index];
        }
    }
    
    for (CommonCouponModel *model in self.platformSysCoupon) {
        if ([model.ucId isEqualToString:sysCouponModel.ucId]) {
            NSInteger index = [self.platformSysCoupon indexOfObject:model];
            self.platformSysCoupon[index].isRec = YES;
            [self refreshDataArray:self.platformSysCoupon AndSelectIndex:index];
        }
    }
    
}

- (void)request_submitOrder {
    
    self.bottomView.submitBtn.userInteractionEnabled = NO;

    NSMutableDictionary *dic = @{}.mutableCopy;
    dic = [self.submitModel modelToJSONObject];

    NSMutableArray *bySellerVoList = @[].mutableCopy;

    for (int i = 0; i < self.submitModel.bySellerVoList.count; i++) {
        
        HandleProSerStoreModel *sellerModel = self.submitModel.bySellerVoList[i];
        NSMutableDictionary *sellerDic = [sellerModel modelToJSONObject];
        
        NSMutableArray *byGoodsVoList = @[].mutableCopy;
        for (int j = 0; j < self.submitModel.bySellerVoList[i].byGoodsVoList.count; j++) {
            HandleProSerModel *model = self.submitModel.bySellerVoList[i].byGoodsVoList[j];
            NSMutableDictionary *goodsDic = [model modelToJSONObject];
            [byGoodsVoList addObject:goodsDic];
        }
        [sellerDic setValue:byGoodsVoList forKey:@"byGoodsVoList"];
        [bySellerVoList addObject:sellerDic];
    }
    [dic setValue:bySellerVoList forKey:@"bySellerVoList"];
    
    if (self.activeType.length > 0) {
        [dic setValue:self.activeType forKey:@"activeType"];
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SubmitPackageOrder];

    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在提交订单"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [SVProgressHUD dismiss];
        weakSelf.bottomView.submitBtn.userInteractionEnabled = YES;

        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                [[BA_BusinessHelper shared] clearBrowseData];

                [weakSelf prepareData];
                [weakSelf request_submitInfoWithType:CouponUseType_none AndScoId:@""];
                
                NSDictionary *dic = [data valueForKey:@"data"];
                SelPayMethodModel *model = [SelPayMethodModel modelWithDictionary:dic];
                SelPayMethodViewController *vc = [[SelPayMethodViewController alloc] init];
                vc.entranceType = PayEntranceType_pro;

                vc.model = model;
//                vc.goodsModel = weakSelf.model.sellerGoodsModel;
                vc.activeType = weakSelf.activeType;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        weakSelf.bottomView.submitBtn.userInteractionEnabled = YES;

    }];
    
}

@end
